import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.14

Item {
    id: loginPage
    
    property var qmlBridge
    property bool isLoggedIn: false
    property string currentUser: ""
    property string currentUserRole: ""
    
    signal loginSuccessful(string username, string role)
    signal loginFailed(string message)
    
    Rectangle {
        anchors.fill: parent
        gradient: Gradient {
            GradientStop { position: 0.0; color: "#2196F3" }
            GradientStop { position: 1.0; color: "#1976D2" }
        }
        
        Rectangle {
            id: loginContainer
            width: 400
            height: 500
            anchors.centerIn: parent
            color: "white"
            radius: 12
            border.color: "#e0e0e0"
            border.width: 1
            
            
            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 40
                spacing: 25
                
                // Logo and Title
                Column {
                    Layout.alignment: Qt.AlignHCenter
                    spacing: 15
                    
                    Rectangle {
                        width: 80
                        height: 80
                        color: "#2196F3"
                        radius: 40
                        anchors.horizontalCenter: parent.horizontalCenter
                        
                        Text {
                            anchors.centerIn: parent
                            text: "🦠"
                            font.pixelSize: 40
                            color: "white"
                        }
                    }
                    
                    Text {
                        text: "Bacteria Sampler System"
                        font.pixelSize: 24
                        font.bold: true
                        color: "#333"
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                    
                    Text {
                        text: "Audit Trail Management"
                        font.pixelSize: 14
                        color: "#666"
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                }
                
                // Login Form
                ColumnLayout {
                    Layout.fillWidth: true
                    spacing: 20
                    
                    // Username Field
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 8
                        
                        Text {
                            text: "Username"
                            font.pixelSize: 14
                            font.bold: true
                            color: "#333"
                        }
                        
                        TextField {
                            id: usernameField
                            Layout.fillWidth: true
                            placeholderText: "Enter your username"
                            font.pixelSize: 14
                            selectByMouse: true
                            
                            background: Rectangle {
                                color: usernameField.focus ? "#f0f8ff" : "#f9f9f9"
                                border.color: usernameField.focus ? "#2196F3" : "#e0e0e0"
                                border.width: 2
                                radius: 6
                            }
                            
                            Keys.onReturnPressed: passwordField.forceActiveFocus()
                        }
                    }
                    
                    // Password Field
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 8
                        
                        Text {
                            text: "Password"
                            font.pixelSize: 14
                            font.bold: true
                            color: "#333"
                        }
                        
                        TextField {
                            id: passwordField
                            Layout.fillWidth: true
                            placeholderText: "Enter your password"
                            echoMode: TextInput.Password
                            font.pixelSize: 14
                            selectByMouse: true
                            
                            background: Rectangle {
                                color: passwordField.focus ? "#f0f8ff" : "#f9f9f9"
                                border.color: passwordField.focus ? "#2196F3" : "#e0e0e0"
                                border.width: 2
                                radius: 6
                            }
                            
                            Keys.onReturnPressed: loginButton.clicked()
                        }
                    }
                    
                    // Remember Me
                    CheckBox {
                        id: rememberMeCheck
                        text: "Remember me"
                        font.pixelSize: 12
                        checked: false
                    }
                    
                    // Error Message
                    Text {
                        id: errorMessage
                        Layout.fillWidth: true
                        text: ""
                        color: "#F44336"
                        font.pixelSize: 12
                        wrapMode: Text.WordWrap
                        visible: text.length > 0
                        
                        Rectangle {
                            anchors.fill: parent
                            anchors.margins: -8
                            color: "#ffebee"
                            border.color: "#F44336"
                            border.width: 1
                            radius: 4
                            visible: parent.visible
                            z: -1
                        }
                    }
                    
                    // Success Message
                    Text {
                        id: successMessage
                        Layout.fillWidth: true
                        text: ""
                        color: "#4CAF50"
                        font.pixelSize: 12
                        wrapMode: Text.WordWrap
                        visible: text.length > 0
                        
                        Rectangle {
                            anchors.fill: parent
                            anchors.margins: -8
                            color: "#e8f5e8"
                            border.color: "#4CAF50"
                            border.width: 1
                            radius: 4
                            visible: parent.visible
                            z: -1
                        }
                    }
                    
                    // Login Button
                    Button {
                        id: loginButton
                        Layout.fillWidth: true
                        Layout.preferredHeight: 45
                        text: "Login"
                        font.pixelSize: 16
                        font.bold: true
                        enabled: usernameField.text.length > 0 && passwordField.text.length > 0
                        
                        background: Rectangle {
                            color: loginButton.enabled ? (loginButton.pressed ? "#1976D2" : "#2196F3") : "#e0e0e0"
                            radius: 6
                            border.color: loginButton.enabled ? "#1976D2" : "#bdbdbd"
                            border.width: 1
                        }
                        
                        contentItem: Text {
                            text: loginButton.text
                            font: loginButton.font
                            color: loginButton.enabled ? "white" : "#9e9e9e"
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }
                        
                        onClicked: performLogin()
                    }
                }
                
                Item { Layout.fillHeight: true }
                
                // Default Users Info
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 80
                    color: "#f5f5f5"
                    radius: 6
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 10
                        spacing: 5
                        
                        Text {
                            text: "Default Users:"
                            font.pixelSize: 12
                            font.bold: true
                            color: "#666"
                            Layout.alignment: Qt.AlignHCenter
                        }
                        
                        Text {
                            text: "admin / admin123 (Administrator)"
                            font.pixelSize: 11
                            color: "#666"
                            Layout.alignment: Qt.AlignHCenter
                        }
                        
                        Text {
                            text: "operator / operator123 (Operator)"
                            font.pixelSize: 11
                            color: "#666"
                            Layout.alignment: Qt.AlignHCenter
                        }
                    }
                }
            }
        }
    }
    
    // Loading Indicator
    Rectangle {
        id: loadingOverlay
        anchors.fill: parent
        color: "#80000000"
        visible: false
        
        Rectangle {
            width: 120
            height: 120
            anchors.centerIn: parent
            color: "white"
            radius: 8
            
            ColumnLayout {
                anchors.centerIn: parent
                spacing: 15
                
                BusyIndicator {
                    Layout.alignment: Qt.AlignHCenter
                    running: loadingOverlay.visible
                }
                
                Text {
                    text: "Logging in..."
                    font.pixelSize: 14
                    color: "#333"
                    Layout.alignment: Qt.AlignHCenter
                }
            }
        }
    }
    
    Component.onCompleted: {
        usernameField.forceActiveFocus()
    }
    
    function performLogin() {
        var username = usernameField.text.trim()
        var password = passwordField.text
        
        if (username.length === 0 || password.length === 0) {
            showError("Please enter both username and password")
            return
        }
        
        clearMessages()
        showLoading(true)
        
        // Simulate login delay
        loginTimer.start()
    }
    
    Timer {
        id: loginTimer
        interval: 1000
        onTriggered: {
            var username = usernameField.text.trim()
            var password = passwordField.text
            
            // Check default users (in real implementation, this would be done via qmlBridge)
            var loginResult = checkCredentials(username, password)
            
            showLoading(false)
            
            if (loginResult.success) {
                currentUser = username
                currentUserRole = loginResult.role
                isLoggedIn = true
                
                // Log successful login
                if (qmlBridge) {
                    console.log("Logging successful login for user:", username)
                    qmlBridge.logUserLogin(username, true)
                }
                
                showSuccess("Login successful! Welcome, " + username)
                
                // Emit login successful signal after a short delay
                successTimer.start()
            } else {
                // Log failed login attempt
                if (qmlBridge) {
                    console.log("Logging failed login attempt for user:", username)
                    // In real implementation: qmlBridge.logUserLogin(username, false)
                }
                
                showError(loginResult.message)
                passwordField.clear()
                passwordField.forceActiveFocus()
            }
        }
    }
    
    Timer {
        id: successTimer
        interval: 1500
        onTriggered: {
            loginSuccessful(currentUser, currentUserRole)
        }
    }
    
    function checkCredentials(username, password) {
        // Default users from database
        var users = {
            "admin": { password: "admin123", role: "administrator" },
            "operator": { password: "operator123", role: "operator" }
        }
        
        if (users.hasOwnProperty(username)) {
            if (users[username].password === password) {
                return {
                    success: true,
                    role: users[username].role,
                    message: "Login successful"
                }
            } else {
                return {
                    success: false,
                    message: "Invalid password for user: " + username
                }
            }
        } else {
            return {
                success: false,
                message: "User not found: " + username
            }
        }
    }
    
    function showError(message) {
        errorMessage.text = message
        successMessage.text = ""
    }
    
    function showSuccess(message) {
        successMessage.text = message
        errorMessage.text = ""
    }
    
    function clearMessages() {
        errorMessage.text = ""
        successMessage.text = ""
    }
    
    function showLoading(show) {
        loadingOverlay.visible = show
    }
    
    function logout() {
        if (qmlBridge && isLoggedIn) {
            console.log("Logging user logout:", currentUser)
            // In real implementation: qmlBridge.logUserLogout(currentUser)
        }
        
        isLoggedIn = false
        currentUser = ""
        currentUserRole = ""
        usernameField.clear()
        passwordField.clear()
        clearMessages()
        usernameField.forceActiveFocus()
    }
}